package org.example.greenhouse.service.impl;


import org.example.greenhouse.dao.TokenDao;
import org.example.greenhouse.entity.Token;
import org.example.greenhouse.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import org.springframework.http.HttpHeaders;
import java.util.HashMap;
import java.util.Map;

@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private RestTemplate restTemplate;

    @Value("${web.url:https://fbox360.com/idserver/core/connect/token}")
    private String url;

    //    @Scheduled(fixedRate = 2 * 60 * 60 * 1000) // 每 2 小时执行一次
    // 发送 POST 请求获取 Token
    @Override
    public Token fetchTokenFromUrl() {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 设置请求体
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("scope", "fbox");
        requestBody.add("client_id", "68db2e8bda8d47b5b5db7eaf71c7dcdd");
        requestBody.add("client_secret", "76dc724c95004acab25482d344dab407");
        requestBody.add("grant_type", "client_credentials");

        // 发送 POST 请求
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestBody, headers);
        ResponseEntity<Token> response = restTemplate.postForEntity(url, request, Token.class);
        // 返回获取的 Token
        return response.getBody();
    }


    // 将 Token 存储到数据库
    @Override
    public void saveToken(Token token) {
        tokenDao.save(token);
    }

    @Override
    // 获取最新的 Token（ID 最大的那个）
    public Token getLatestToken() {
        return tokenDao.findTopByOrderByIdDesc();
    }
}
